<script>
import TitleA from "@/comps/comm/TitleA.vue";
import EmpHolder from "@/pages/v1/mes/Flow/js/starter/EmpHolder.vue";
import QrCodeHolder from "@/pages/v1/mes/Flow/js/starter/QrCodeHolder.vue";
import apiFlow from "@/pages/v1/mes/Flow/js/apiFlow";
import formBuilder from "@/comps/form/formBuilder";
import EzData from "@/comps/EzData.vue";
import apiPaper from "@/pages/v1/mes/Paper/js/apiPaper";
import TitleAW from "@/comps/comm/TitleAW.vue";
import TitleB from "@/comps/comm/TitleB.vue";
import apiPlan from "@/pages/v1/mes/Plan/js/apiPlan";

export default {
  components: {TitleB, TitleAW, EzData, QrCodeHolder, EmpHolder, TitleA},
  data() {
    let fb = formBuilder()
    fb.setLabelPosition("right").setLabelWidth(70)
    // fb.addBlank("_blank2", "", 3)
    fb.addBlank("_blank1", "工序", 12)
    fb.addText("numSuccess", "成品", 4).setTextTypeNumber()
    fb.addText("numFail", "修品", 4).setTextTypeNumber()
    fb.addText("numWast", "废品", 4).setTextTypeNumber()
    fb.addBlank("_blank", "", 12)
    return {
      rowConfig: fb,
      emp: {name: "NA"},
      autoCalc: true,
      // plan:"200240716.21.192",
      plan: {sn: "", product: ""},
      parent: {sn: "", product: ""},
      step: 1,
      flow: null,
      curPaper: {
        processId: 0,
        flowId: 0,
        numSuccess: 0,
        numFail: 0,
        numWast: 0,
        empId: 0,
        srcPapers:[],
      },
      papers: [],
      upperPapers: [],
      upDateKey:"",
    }
  },
  mounted() {
  },
  methods: {
    // createPaperLink(srcPaperId,numUse,processName){
    createPaperLink(paper){
      return {
        srcPaperId:paper.id,
        numUse:paper.numSuccess-paper.numUsed,
        processName:paper.process.name,
        flowSn:paper.flow.sn,
      }
    },
    addToSrcPaper(paper){
      this.curPaper.srcPapers.push(this.createPaperLink(paper))
      this.reCalcNum()
    },
    reCalcNum(){
      let num = 0
      for (let row of this.curPaper.srcPapers) {
        num += row.numUse*1
      }

      if (this.autoCalc){
        this.curPaper.numSuccess = num - this.curPaper.numFail - this.curPaper.numWast
      }else {
        this.curPaper.numSuccess = num
      }
      // this.upDateKey =Math.random()
    },
    removePaperLink(index){
      this.curPaper.srcPapers = this.$utils.arrayDelIndex(this.curPaper.srcPapers,index)
    },
    setEmp() {
      this.step = 1
      this.curPaper.empId = this.emp.id
    },
    setPlan(plan, code) {
      this.step = 2
      this.checkAndStart(plan, code)
      this.getPlan(code)
    },
    getPlan(code){
      let arr = code.split(".")
      if (arr.length > 0){
        apiPlan.findBy({_where:{sn:arr[0]},_dumps:["template.processes"]},res=>{
          if (res.length > 0){
            this.plan = res[0]
          }
        })
      }
    },
    checkAndStart(plan, code) {
      apiFlow.checkAndStart(code, res => {
        this.flow = res.data
        this.curPaper.flowId = this.flow.id
        this.getFlowPapers()
        //设置一些默认值
        //1.默认把当前跟踪单号当做前序跟踪单号
        this.setParent(plan, code)


      })
    },
    createNewPaper() {

      if (this.curPaper.flowId === 0) {
        this.$toast.error("请扫码跟踪单")
        return
      }
      if (this.curPaper.processId === 0) {
        this.$toast.error("请选择工序")
        return
      }
      if (this.curPaper.numSuccess + this.curPaper.numFail + this.curPaper.numWast === 0) {
        this.$toast.error("请输入数量")
        return
      }
      apiPaper.saveManuel(this.curPaper, res => {
        this.getFlowPapers()
        // location.reload()
      })
    },
    getFlowPapers() {
      if (this.flow.id * 1 === 0) {
        this.$toast.error("未找到跟踪单")
      } else {
        apiPaper.findBy({
          _where: {flowId: this.flow.id},
          _dumps: ["flow", "process"],
          page: 1,
          limit: 10000
        }, res => {
          this.papers = res
        })
      }
    },
    setProcess(id) {
      this.curPaper.processId = id
    },
    setParent(plan, code) {
      apiPaper.findBy({
        _where: {
          'flow.sn': code,
        },
        _dumps: ["flow", "process"],
        page: 1,
        limit: 10000
      }, res => {
        for (let row of res) {
          row.selected = false
        }
        this.upperPapers = res
        //默认从当前工序中没有使用完成的工序座位linkSrc
        for (const paper of this.upperPapers) {
          if (paper.numSuccess - paper.numUsed > 0){
            this.addToSrcPaper(paper)
            //默认设置当前工序的后面工序为指定工序
            let find = false
            for (let process of this.plan.template.processes) {
              if (find){
                this.setProcess(process.id)
                break
              }
              if (process.id === paper.processId){
                find = true
              }
            }

            return
          }
        }
      })
    }
  },
  watch: {
    "curPaper.numFail"(){
      this.reCalcNum()
    },
    "curPaper.numWast"(){
      this.reCalcNum()
    },
  }


}
</script>

<template>
  <div class="pad5 flex-r flex-start">
    <div class="flex1">
      <div class="bcf round3">
        <div class="round3 pad5 marb5">
          <div class="flex-r">
            <div class="flex1 marr10 pad5 bcf bdso bdc04 bdw1 round3">
              <title-a>报工区</title-a>
              <div class="flex-r flex-end">
                <div class="flex-start flex1">
                  <EmpHolder :emp.sync="emp" @update:emp="setEmp"></EmpHolder>
                </div>
                <div class="">
                  <QrCodeHolder title="扫描跟踪单" @input="setPlan" key="plan"></QrCodeHolder>
                </div>
              </div>
              <div class="flrc bc13 padtb5">
                <div class="flex1">
                  <span>人员：</span>
                  <span>{{ emp.name }}</span>
                </div>
                <div class="flex1">
                  <span>产品：</span>
                  <span>{{ plan.product }}</span>
                </div>
                <div class="flex1">
                  <span>排产单：</span>
                  <span>{{ plan.sn }}</span>
                </div>
              </div>
              <EzData ref="form" :config="rowConfig" v-model="curPaper" :key="upDateKey">
                <div slot="_blank1" class="">
                  <div v-if="plan.template && plan.template.processes.length > 0" class="">
                    <mu-button @click="setProcess(item.id)" :color="curPaper.processId !== item.id ? 'primary' : 'secondary'"
                               v-for="(item,index) in plan.template.processes" :key="index">
                      {{ item.name }}
                    </mu-button>
                  </div>
                  <div class="" v-else>暂无数据</div>
                </div>
                <div slot="_blank" class="flrc w100">
                  <div class="flex1 tar"><mu-switch v-model="autoCalc" label="自动计算"></mu-switch></div>
                  <mu-button @click="createNewPaper" small color="success" round>保存</mu-button>
                </div>
              </EzData>
              <div class="flrc bc13 padtb3">
                <div class="flex1">跟踪单号</div>
                <div class="flex1">ID</div>
                <div class="flex1">工序</div>
                <div class="flex1">用量</div>
                <div class="flex1 tar">操作</div>
              </div>
              <div class="flrc bdbda" v-for="(paper,index) in curPaper.srcPapers" :key="index">
                <div class="flex1">{{paper.flowSn}}</div>
                <div class="flex1">{{paper.srcPaperId}}</div>
                <div class="flex1">{{paper.processName}}</div>
                <div class="flex1 padt3">
                  <mu-text-field solo type="number" v-model.number="paper.numUse" style="width: 150px;"></mu-text-field>
                </div>
                <div class="flex1 tar"><mu-button @click="removePaperLink(index)" icon><mu-icon value="close"></mu-icon></mu-button></div>
              </div>
            </div>
            <div class="flex1 bcf pad5">
              <title-b>分单/合单</title-b>
              <div class="flex-r flex-start">
                <QrCodeHolder title="前序跟踪单" v-model="parent" @input="setParent" key="parent"></QrCodeHolder>
              </div>
              <div class="flrc bc13 padtb3">
                <div class="flex1">选择</div>
                <div class="flex1">工序</div>
                <div class="flex1">成品 / 修 / 废</div>
                <div class="flex1">已使用</div>
                <div class="flex1">时间</div>
              </div>
              <div class="flrc" v-for="(paper,index) in upperPapers" :key="index">
                <div class="flex1">
                  <mu-button @click="addToSrcPaper(paper)" icon>
                    <mu-icon value="arrow_left"></mu-icon>
                  </mu-button>
                </div>
                <div class="flex1" v-if="paper.process">{{ paper.process.name }}</div>
                <div class="flex1" v-else>--</div>
                <div class="flex1">
                  <span>{{ paper.numSuccess }}</span>
                  (<span class="c12">{{ paper.numFail }}</span>
                  <span class="c12">/{{ paper.numWast }}</span>)
                </div>
                <div class="flex1">
                  <span class="">{{ paper.numUsed }}</span>
                  (<span
                    :class="{'c12':paper.numSuccess - paper.numUsed <= 0,'mdui-text-color-green fwb':paper.numSuccess - paper.numUsed > 0}">{{
                    paper.numSuccess - paper.numUsed
                  }}</span>)
                </div>
                <div class="flex1">{{ $utils.str2date(paper.createAt) }}</div>

              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="bcf mart5 pad5 round3">
        <title-a>历史数据</title-a>
        <div v-if="papers.length > 0" class="pad3 mart10">
          <div class="flrc">
            <div class="flex1">工序</div>
            <div class="flex1">成品</div>
            <div class="flex1">修品</div>
            <div class="flex1">废品</div>
            <div class="flex1">时间</div>
            <div class="flex1 tar">操作</div>
          </div>
          <div class="flrc" v-for="(paper,index) in papers" :key="index">
            <div class="flex1" v-if="paper.process">{{ paper.process.name }}</div>
            <div class="flex1" v-else>--</div>
            <div class="flex1">{{ paper.numSuccess }}</div>
            <div class="flex1">{{ paper.numFail }}</div>
            <div class="flex1">{{ paper.numWast }}</div>
            <div class="flex1">{{ $utils.str2time(paper.createAt) }}</div>
            <div class="flex1 tar">
              <mu-button icon>
                <mu-icon value="close"></mu-icon>
              </mu-button>
            </div>
          </div>
        </div>
        <div class="mar10 pad20 bdda tac bc13" v-else>暂无数据</div>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>